var app = angular.module('main', ['ngTable','angularFileUpload','LocalStorageModule']).
    config(function(localStorageServiceProvider){
      localStorageServiceProvider.setPrefix('shanbay');
    }).
    controller('DemoCtrl', function($scope, NgTableParams,FileUploader,localStorageService,$http) {
        //获取缓存
        var decodeLocal=function(){
            var str = localStorageService.get('words');
            if(str){
                $scope.data = JSON.parse(str);
                for (var i = 0; i < $scope.data.length; i++) {
                    $scope.data[i]['state']='';
                }
                return;
            }
            $scope.data = [];
        }
        //更新缓存
        var updateData = function(){
            $scope.tableParams.reload();
            localStorageService.set("words",JSON.stringify($scope.data));
        }
        decodeLocal();
        $scope.tableParams =  new NgTableParams({
                 // page: 1,            // show first page
                  count: 1000           // count per page
            }, 
            {
                counts:[],
                total: $scope.data.length, // length of data
                getData: function($defer, params) {
                    $defer.resolve($scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                }
            });

        var uploader = $scope.uploader = new FileUploader({
            url: 'upload.php'
        });
        uploader.onAfterAddingFile = function(fileItem) {
            decodeFile(document.getElementById('input_file').files,function(data){
                $scope.data=data;
                updateData();
            });
        };

        $scope.submit = function(){
            submitWords();
        }
        $scope.getFirstTen = function(){
            var ten = $scope.data.splice(0,10);
            updateData();
            var str = "";
            for (var i = 0; i < ten.length; i++) {
                str+=ten[i].word + "\n";
            }
            if(str){
                window.prompt("复制到剪切板: Ctrl+C, Enter", str);
            }

        }
        //解析文件
        var decodeFile = function(files,fn){
            if (!files || files.length === 0) {
                return;
            }
            var file = files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var contents = e.target.result;
                var regex = new RegExp(/(\d{1,}),\s{0,}(([a-zA-Z]{1,}[ |-]{0,}){1,})(\[|\s)/g);
                var records = [];
                var b;
                var i = 1;
                while (b = regex.exec(contents)) {
                    if (b.length > 2) {
                        var r = {
                                //id: i++,
                                num: b[1],
                                word: b[2].trim()
                            };
                        records.push(r);
                    }
                }
                fn(records);

            };
            reader.readAsText(file);
        }
        var removeData = function(index){
            $scope.data.splice(index,1);
            updateData();
        }


     var haveUsed = 0, //已经使用次数
        maxUsed=105;//最大提交次数
     var submitWords =function(){
        // if(maxUsed <=haveUsed){
        //     window.alert("导入次数过多!!请1小时后再来或手动导入");
        //     return;
        // }
        for (var i = 0; i < $scope.data.length; i++) {
            $scope.data[i].state="";
        }        
       
        updateData();
        addWords(0);
    };
    
    var addWords = function(index){
        var data = $scope.data
        haveUsed ++;
        var count = data.length;
         if(count === 0 || index >= count){
            return ;
        }
        var r = data[index];
        r["state"] ="提交中";
        updateData();
        $http({
            method:"post",
            url:"AddWord.aspx?action=addword",
            params:{
                word:r["word"],
            }
        }).then(function(response){
            var ret = response.data;
            if(ret.success==="true")
            {
                removeData(index);
                addWords(index);
            }
            else if(ret.err_code == 1){
                location.href = ret.url;
            }
            else
            {
                if(ret.msg.indexOf('405')>=0){
                    r["state"]="访问次数过多,请1小时后再来或手动导入";
                    window.alert("导入次数过多!!请1小时后再来或手动导入");
                    updateData();
                }else{
                    r["state"]=ret.msg;
                    addWords(index+1);
                }

            }
        },function(response){
            r["state"] = response.responseText;
        });
    };
    });
